package com.skivingcloud.admin.sys.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.skivingcloud.admin.sys.entity.SysOrg;
import com.skivingcloud.admin.sys.mapper.SysOrgMapper;
import com.skivingcloud.admin.sys.service.SysOrgService;
import com.skivingcloud.common.utils.PageParameter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *  服务层实现。
 *
 * @author skivingcloud
 * @since 2023-08-28
 */
@Service
public class SysOrgServiceImpl extends ServiceImpl<SysOrgMapper, SysOrg> implements SysOrgService {
    
    /**
     * 分页查询机构
     *
     * @param parameter 参数
     * @return 分页结果
     */
    @Override
    public Page<SysOrg> queryByPage(PageParameter<SysOrg> parameter){
        Page<SysOrg> page = new Page<>(parameter.getPage(), parameter.getPageSize());
        SysOrg sysOrg = parameter.getParam();
        QueryWrapper queryWrapper = QueryWrapper.create().where(" 1=1 ");
        if(sysOrg != null){
            if(StringUtils.isNotBlank(sysOrg.getOrgCode())){
                queryWrapper.and(SysOrg::getOrgCode).like(sysOrg.getOrgCode());
            }
            if(StringUtils.isNotBlank(sysOrg.getOrgName())){
                queryWrapper.and(SysOrg::getOrgName).like(sysOrg.getOrgName());
            }
        }
        queryWrapper.orderBy(SysOrg::getOrderNum);
        return this.page(page, queryWrapper);
    }
    
    /**
     * 查询机构树形
     *
     * @param tenantId 租户ID
     * @return 机构树形
     */
    @Override
    @Cacheable(value="skivingOrg", key="#p0 + '_queryOrgTreeByTenantId'")
    public List<SysOrg> getAllOrgTreeUtils(String tenantId){
        QueryWrapper queryWrapper = QueryWrapper.create().where(SysOrg::getTenantId).eq(tenantId);
        List<SysOrg> list = this.mapper.selectListByQuery(queryWrapper);
        return list.stream().filter(item -> {
            item.setChildren(list.stream().filter(e -> e.getParentId().equals(item.getId())).toList());
            return item.getParentId().equals("0");
        }).toList();
    }
    
    /**
     * 查询机构树形
     *
     * @return 查询机构树形
     */
    @Override
    @Cacheable(value="skivingOrg", key="#p0 + '_queryOrgTreeByAdmin'")
    public List<SysOrg> getAllOrgTreeUtils(){
        List<SysOrg> list = this.mapper.selectAll();
        return list.stream().filter(item -> {
            item.setChildren(list.stream().filter(e -> e.getParentId().equals(item.getId())).toList());
            return item.getParentId().equals("0");
        }).toList();
    }
}
